﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace RandomSelect
{
    class Request
    {

        //PostRequest("http://tinywebdb.appinventor.space/api");
        //GetRequest("http://www.baidu.com");

        private static string URL = "";
        public string value = "";

        public void SetUrl(string argUrl)
        {
            URL = argUrl;
        }

        public async Task<string> GetRequest(string url)
        {
            HttpClient client = new HttpClient();
            
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                    string myContent = await content.ReadAsStringAsync();
                    string picUrl = "";
                    string picInf = "";
                    HttpContentHeaders headers = content.Headers;
                    //Console.WriteLine(myContent);
                    picUrl = "https://cn.bing.com" + myContent.Substring(myContent.IndexOf("<url>")+5, myContent.IndexOf("</url>") - myContent.IndexOf("<url>") - 5);
                    picInf = "https://cn.bing.com" + myContent.Substring(myContent.IndexOf("<copyright>") + 11, myContent.IndexOf("</copyright>") - myContent.IndexOf("<copyright>") - 11);
                    //Console.WriteLine(picUrl);
                    return picUrl + "~" + picInf;
                }
            }
        }

        public async Task<string> PostRequest(string key, string action, string val = "")
        {
            IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("user", "rdsbyhy"),
                new KeyValuePair<string, string>("secret", "c8b6f495"),
                new KeyValuePair<string, string>("action", action),
                new KeyValuePair<string, string>("value", val),
                new KeyValuePair<string, string>("count", "20"),
                new KeyValuePair<string, string>("no", "1"),
                new KeyValuePair<string, string>("tag", key)
            };
            HttpContent q = new FormUrlEncodedContent(queries);
            HttpClient client = new HttpClient();
            
            using (HttpResponseMessage response = await client.PostAsync(URL, q))
            {
                using (HttpContent content = response.Content)
                {
                    string myContent = await content.ReadAsStringAsync();
                    HttpContentHeaders headers = content.Headers;
                    //Console.WriteLine(myContent);
                    value = myContent.Replace("\"", "").Replace(" ", "").Replace("{", "").Replace("}", "").Split(':')[1];
                    Console.WriteLine(value);
                    return value;
                }
            }
        }
    }
}
